/**
 * 微信支付工具类
 */
import { post, get } from './request.js'

/**
 * 发起支付
 * @param {Object} orderData - 订单数据
 * @param {string} orderData.orderId - 订单ID
 * @param {string} orderData.openid - 用户openid
 * @returns {Promise} 支付结果
 */
export const initiatePayment = async (orderData) => {
  try {
    console.log('🚀 发起支付请求:', orderData);

    // 调用后端支付接口
    const response = await post(`/api/parking/orders/${orderData.orderId}/pay`, {
      openid: orderData.openid
    });

    if (!response.success) {
      throw new Error(response.message || '支付下单失败');
    }

    const paymentParams = response.data.payment_params;

    console.log('💳 调起微信支付:', paymentParams);

    // 检查是否为模拟模式
    if (paymentParams.mockMode) {
      console.log('🎭 模拟支付模式');

      // 显示模拟支付提示并等待用户选择
      const mockResult = await new Promise((resolve) => {
        uni.showModal({
          title: '模拟支付',
          content: '当前为开发模式，将模拟支付成功。实际部署时请配置真实的微信支付证书。',
          showCancel: true,
          cancelText: '取消支付',
          confirmText: '模拟成功',
          success: (res) => {
            resolve(res);
          }
        });
      });

      if (!mockResult.confirm) {
        return { success: false, cancelled: true, message: '用户取消支付' };
      }

      // 调用模拟支付成功接口
      try {
        const mockPayResponse = await post(`/api/parking/orders/${orderData.orderId}/mock-pay`, {});

        if (mockPayResponse.success) {
          return { success: true, mock: true, data: mockPayResponse.data };
        } else {
          throw new Error(mockPayResponse.message || '模拟支付失败');
        }
      } catch (error) {
        console.error('模拟支付接口调用失败:', error);
        return { success: false, message: '模拟支付失败' };
      }
    }

    // 调起真实微信支付
    const payResult = await new Promise((resolve, reject) => {
      uni.requestPayment({
        timeStamp: paymentParams.timeStamp,
        nonceStr: paymentParams.nonceStr,
        package: paymentParams.package,
        signType: paymentParams.signType,
        paySign: paymentParams.paySign,
        success: async (res) => {
          console.log('✅ 支付成功:', res);

          // 支付成功后立即查询支付状态，更新服务器端订单状态
          try {
            console.log('🔄 支付成功，正在更新订单状态...');
            const statusResult = await queryPaymentStatus(orderData.orderId);
            console.log('📋 订单状态更新结果:', statusResult);
            resolve({ success: true, data: res, orderStatus: statusResult });
          } catch (error) {
            console.error('❌ 更新订单状态失败:', error);
            // 即使更新状态失败，也返回支付成功，因为微信支付已经成功了
            resolve({ success: true, data: res, statusUpdateError: error.message });
          }
        },
        fail: (err) => {
          console.log('❌ 支付失败:', err);
          if (err.errMsg === 'requestPayment:fail cancel') {
            resolve({ success: false, cancelled: true, message: '用户取消支付' });
          } else {
            reject(new Error(err.errMsg || '支付失败'));
          }
        }
      });
    });

    return payResult;

  } catch (error) {
    console.error('支付过程出错:', error);
    return {
      success: false,
      message: error.message || '支付失败'
    };
  }
};

/**
 * 直接使用后端返回的微信支付参数调起支付（用于尾款等场景）
 * @param {Object} paymentParams - 后端返回的小程序支付参数
 * @param {string} orderId - 订单ID（用于支付成功后查询状态）
 * @returns {Promise<{success:boolean, cancelled?:boolean, mock?:boolean}>}
 */
export const invokePaymentParams = async (paymentParams, orderId = null) => {
  try {
    // 模拟模式：提示并直接返回成功（注意：服务器可能不会自动更新状态）
    if (paymentParams.mockMode) {
      const modal = await new Promise((resolve) => {
        uni.showModal({
          title: '模拟支付',
          content: '当前为开发/模拟模式，将模拟支付成功。实际部署请使用真实支付。',
          showCancel: true,
          cancelText: '取消',
          confirmText: '模拟成功',
          success: resolve
        })
      })
      if (!modal.confirm) return { success: false, cancelled: true }
      return { success: true, mock: true }
    }

    // 真实支付
    const payRes = await new Promise((resolve, reject) => {
      uni.requestPayment({
        timeStamp: paymentParams.timeStamp,
        nonceStr: paymentParams.nonceStr,
        package: paymentParams.package,
        signType: paymentParams.signType,
        paySign: paymentParams.paySign,
        success: async (res) => {
          console.log('✅ 尾款支付成功:', res);

          // 如果提供了订单ID，支付成功后立即查询支付状态，确保服务器端状态同步
          if (orderId) {
            try {
              console.log('🔄 尾款支付成功，正在更新订单状态...');
              const statusResult = await queryPaymentStatus(orderId);
              console.log('📋 尾款订单状态更新结果:', statusResult);
              resolve({ success: true, data: res, orderStatus: statusResult });
            } catch (error) {
              console.error('❌ 更新尾款订单状态失败:', error);
              // 即使更新状态失败，也返回支付成功，因为微信支付已经成功了
              resolve({ success: true, data: res, statusUpdateError: error.message });
            }
          } else {
            resolve({ success: true, data: res });
          }
        },
        fail: (err) => {
          if (err.errMsg === 'requestPayment:fail cancel') {
            resolve({ success: false, cancelled: true })
          } else {
            reject(err)
          }
        }
      })
    })

    return payRes
  } catch (err) {
    console.error('invokePaymentParams 调起支付失败:', err)
    return { success: false, message: err?.message || '支付失败' }
  }
}


/**
 * 查询支付状态
 * @param {string} orderId - 订单ID
 * @returns {Promise} 支付状态
 */
export const queryPaymentStatus = async (orderId) => {
  try {
    const response = await get(`/api/parking/orders/${orderId}/payment-status`);

    if (response.success) {
      return response.data;
    } else {
      throw new Error(response.message || '查询失败');
    }

  } catch (error) {
    console.error('查询支付状态失败:', error);
    throw error;
  }
};

/**
 * 获取用户openid
 * @returns {Promise<string>} openid
 */
export const getUserOpenid = async () => {
  try {
    // 先检查本地存储
    let cachedOpenid = null;
    try {
      const userInfoStr = uni.getStorageSync('userInfo');
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr);
        cachedOpenid = userInfo.openid;
      }
    } catch (error) {
      console.warn('解析用户信息失败:', error);
    }

    console.log('本地存储中的用户信息:', uni.getStorageSync('userInfo'));
    console.log('从本地存储获取的openid:', cachedOpenid);
    if (cachedOpenid) {
      return cachedOpenid;
    }

    // 检查是否在微信小程序环境中
    let isWechatMiniProgram = false;

    // #ifdef MP-WEIXIN
    isWechatMiniProgram = true;
    // #endif

    let code;

    if (!isWechatMiniProgram) {
      // 非微信小程序环境，使用模拟code
      console.log('🎭 非微信小程序环境，使用模拟code');
      code = 'mock_code_' + Date.now();
    } else {
      // 获取登录凭证
      const loginResult = await new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: resolve,
          fail: reject
        });
      });

      if (!loginResult.code) {
        throw new Error('获取登录凭证失败');
      }

      code = loginResult.code;
    }

    // 调用后端接口获取openid
    const response = await post('/api/auth/get-openid', {
      code: code
    });

    if (response.success && response.data.openid) {
      const openid = response.data.openid;
      // 缓存openid
      uni.setStorageSync('openid', openid);
      return openid;
    } else {
      throw new Error('获取openid失败');
    }

  } catch (error) {
    console.error('获取openid失败:', error);

    // 如果获取失败，在开发环境中使用模拟openid
    console.log('🎭 获取openid失败，使用模拟openid');
    const mockOpenid = 'mock_openid_' + Date.now();
    uni.setStorageSync('openid', mockOpenid);
    return mockOpenid;
  }
};

/**
 * 轮询支付状态
 * @param {string} orderId - 订单ID
 * @param {number} maxAttempts - 最大轮询次数
 * @param {number} interval - 轮询间隔(毫秒)
 * @returns {Promise} 最终支付状态
 */
export const pollPaymentStatus = async (orderId, maxAttempts = 10, interval = 2000) => {
  for (let i = 0; i < maxAttempts; i++) {
    try {
      const status = await queryPaymentStatus(orderId);

      if (status.status === 'in_progress') {
        return { success: true, status: 'paid', data: status };
      } else if (status.status === 'cancelled') {
        return { success: false, status: 'cancelled', data: status };
      }

      // 如果还是pending_payment状态，继续轮询
      if (i < maxAttempts - 1) {
        await new Promise(resolve => setTimeout(resolve, interval));
      }

    } catch (error) {
      console.error(`第${i + 1}次查询支付状态失败:`, error);
      if (i === maxAttempts - 1) {
        throw error;
      }
    }
  }

  return { success: false, status: 'timeout', message: '支付状态查询超时' };
};